<template>
  <div>
    <el-form ref="SpuForm" :model="SpuForm" label-width="100px">
      <el-form-item label="SPU名称">
        <el-input v-model="SpuForm.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="SpuForm.tmId">
          <el-option
            v-for="item in trademarkList"
            :key="item.id"
            :label="item.tmName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          v-model="SpuForm.description"
          rows="4"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-success="handlePictureCardSuccess"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :file-list="spuImageList"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          v-model="saleAttrIdandName"
          :placeholder="
            unUsedsaleAttrList.length > 0
              ? `还有${unUsedsaleAttrList.length}种未选择`
              : '没有了'
          "
        >
          <el-option
            :label="attr.name"
            v-for="attr in unUsedsaleAttrList"
            :key="attr.id"
            :value="`${attr.id}:${attr.name}`"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icons-plus"
          @click="addSaleAttr"
          :disabled="!saleAttrIdandName"
          >添加销售属性</el-button
        >
      </el-form-item>
      <el-table :data="SpuForm.spuSaleAttrList" style="width: 100%">
        <el-table-column align="center" type="index" label="序号" width="width">
        </el-table-column>
        <el-table-column width="width" prop="saleAttrName" label="属性名">
        </el-table-column>
        <el-table-column width="width" prop="prop" label="属性值名称列表">
          <template slot-scope="{ row, $index }">
            <!-- -->
            <!-- 
              -->
            <el-tag
              :key="AttrValue.id"
              v-for="(AttrValue, index) in row.spuSaleAttrValueList"
              closable
              :disable-transitions="false"
              @close="row.spuSaleAttrValueList.splice(index, 1)"
            >
              {{ AttrValue.saleAttrValueName }}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="row.inputVisible"
              v-model="row.inputValue"
              ref="saveTagInput"
              size="small"
              @blur="handleInputConfirm(row)"
              @keyup.enter.native="handleInputConfirm(row)"
            >
            </el-input>
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput(row)"
              >+ 添加</el-button
            >
          </template>
        </el-table-column>
        <el-table-column width="width" prop="prop" label="操作">
          <template slot-scope="{ row, $index }">
            <HintButton
              title="删除销售属性"
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="SpuForm.spuSaleAttrList.splice($index, 1)"
            ></HintButton>
          </template>
        </el-table-column>
      </el-table>
      <el-form-item style="margin-top: 10px">
        <el-button type="primary" @click="saveAttr">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "spuForm",
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      saleAttrIdandName: "",
      SpuForm: {
        category3Id: 0,
        description: "",
        tmId: "",

        spuImageList: [
          // {
          //   id: 0,
          //   imgName: "string",
          //   imgUrl: "string",
          //   spuId: 0,
          // },
        ],
        spuName: "",
        spuSaleAttrList: [
          // {
          //   baseSaleAttrId: 0,
          //   id: 0,
          //   saleAttrName: "string",
          //   spuId: 0,
          //   spuSaleAttrValueList: [
          //     {
          //       baseSaleAttrId: 0,
          //       id: 0,
          //       isChecked: "string",
          //       saleAttrName: "string",
          //       saleAttrValueName: "string",
          //       spuId: 0,
          //     },
          //   ],
          // },
        ],
      },
      spuImageList: [],
      trademarkList: [],
      baseSaleAttrList: [],
    };
  },
  methods: {
    async getInitUpdateFormData(id, category3Id) {
      let result1 = await this.$API.spu.get(id);
      if (result1.code === 200) {
        this.SpuForm = result1.data;
        this.SpuForm.category3Id = category3Id;
      }
      let result2 = await this.$API.sku.getSpuImageList(id);
      if (result2.code === 200) {
        let spuImageList = result2.data;
        spuImageList.forEach((item) => {
          item.url = item.imgUrl;
          item.name = item.imgName;
        });
        this.spuImageList = spuImageList;
      }
      let result3 = await this.$API.trademark.getList();
      if (result3.code === 200) {
        this.trademarkList = result3.data;
      }
      let result4 = await this.$API.spu.getSaleAttrList();
      if (result4.code === 200) {
        this.baseSaleAttrList = result4.data;
      }
    },
    async getInitAddFormData(category3Id) {
      this.SpuForm.category3Id = category3Id;
      let result3 = await this.$API.trademark.getList();
      if (result3.code === 200) {
        this.trademarkList = result3.data;
      }
      let result4 = await this.$API.spu.getSaleAttrList();
      if (result4.code === 200) {
        this.baseSaleAttrList = result4.data;
      }
    },
    handleRemove(file, fileList) {
      this.spuImageList = fileList;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePictureCardSuccess(response, file, fileList) {
      this.spuImageList = fileList;
      console.log(fileList);
    },
    cancel() {
      this.$emit("update:visible", false);
      this.resetData()
    },
    addSaleAttr() {
      let [baseSaleAttrId, saleAttrName] = this.saleAttrIdandName.split(":");
      let obj = {
        saleAttrName,
        baseSaleAttrId,
        spuSaleAttrValueList: [],
      };
      this.SpuForm.spuSaleAttrList.push(obj);
      this.saleAttrIdandName = "";
    },
    showInput(row) {
      this.$set(row, "inputVisible", true);
      this.$set(row, "inputValue", "");
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus();
      });
    },
    handleInputConfirm(row) {
      let { inputValue, baseSaleAttrId } = row;
      if (inputValue.trim() === "") {
        row.inputValue = "";
        return;
      }
      let isRepeat = row.spuSaleAttrValueList.some(
        (item) => item.saleAttrValueName === inputValue
      );
      if (isRepeat) {
        this.$message.error("输入的值重复了");
        row.inputValue = "";
        return;
      }
      let obj = {
        saleAttrValueName: inputValue,
        baseSaleAttrId,
      };
      row.spuSaleAttrValueList.push(obj);
      row.inputValue = "";
      row.inputVisible = false;
    },
    async saveAttr() {
      let { SpuForm, spuImageList } = this;
      if (spuImageList.length === 0) {
        this.$message.error("您必须上传图片");
        return;
      }
      SpuForm.spuImageList = spuImageList.map((item) => {
        return {
          imgName: item.name,
          imgUrl: item.imgUrl || item.response.data,
        };
      });
      SpuForm.spuSaleAttrList.forEach((item) => {
        delete item.inputVisible;
        delete item.inputValue;
      });
      try {
        let result = await this.$API.spu.addUpdate(SpuForm);
        if (result.code === 200 || result.code === 20000) {
          this.$message.success(SpuForm.id ? "修改属性成功" : "添加属性成功");
          this.$emit("update:visible", false);
          this.$emit("backsuccess");
          this.resetData();
        }
      } catch (e) {
        this.$message.error(
          SpuForm.id ? "修改属性失败" : "添加属性失败" + e.message
        );
      }
    },
    resetData() {
      this.dialogImageUrl = "";
      this.dialogVisible = false;
      this.saleAttrIdandName = "";
      (this.SpuForm = {
        category3Id: 0,
        description: "",
        tmId: "",

        spuImageList: [
          // {
          //   id: 0,
          //   imgName: "string",
          //   imgUrl: "string",
          //   spuId: 0,
          // },
        ],
        spuName: "",
        spuSaleAttrList: [
          // {
          //   baseSaleAttrId: 0,
          //   id: 0,
          //   saleAttrName: "string",
          //   spuId: 0,
          //   spuSaleAttrValueList: [
          //     {
          //       baseSaleAttrId: 0,
          //       id: 0,
          //       isChecked: "string",
          //       saleAttrName: "string",
          //       saleAttrValueName: "string",
          //       spuId: 0,
          //     },
          //   ],
          // },
        ],
      }),
        (this.spuImageList = []);
      this.trademarkList = [];
      this.baseSaleAttrList = [];
    },
  },
  computed: {
    unUsedsaleAttrList() {
      return this.baseSaleAttrList.filter((item1) => {
        return this.SpuForm.spuSaleAttrList.every((item2) => {
          return item2.saleAttrName !== item1.name;
        });
      });
    },
  },
};
</script>

<style lang="scss">
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>